package com.shop.admin.service.pink;


import com.alibaba.fastjson.JSON;
import com.shop.admin.service.user.UserPinkBillService;
import com.shop.admin.dao.pink.*;
import com.shop.admin.dao.user.*;
import com.shop.common.enums.TrueFalseEnum;
import com.shop.common.enums.user.BillTableNameEnum;
import com.shop.common.enums.user.IncomeTypeEnum;
import com.shop.domain.pink.*;
import com.shop.domain.user.User;
import com.shop.util.DateUtil;
import com.shop.util.RandomUtil;
import com.shop.web.cache.RedisCache;
import com.shop.web.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional
public class StoreSnapPinkService {

    @Autowired
    private StoreSnapPinkDao storeSnapPinkDao;

    @Autowired
    private SnapRedPinkDao snapRedPinkDao;

    @Autowired
    private StoreSnapPinkConfigDao storeSnapPinkConfigDao;

    @Autowired
    private UserPinkBillDao userPinkBillDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserSnapPinkInfoDao userSnapPinkInfoDao;

    @Autowired
    private UserBillDao userbillDao;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserPinkBillService userPinkBillService;




    /**
     * 执行拼团
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public BaseResponse exeStorePink() {

        long time=System.currentTimeMillis();

        //1,查询拼团配置信息
        StoreSnapPinkConfig storePinkConfig = storeSnapPinkConfigDao.findSingle(2l);

        if(storePinkConfig.getStatus().equals(TrueFalseEnum.FALSE.getCode())
          || !DateUtil.isEffectiveDate(DateUtil.parseTime(DateUtil.formatTime(new Date())),DateUtil.parseTime(storePinkConfig.getStartTime()),DateUtil.parseTime(storePinkConfig.getEndTime()))){
            return new BaseResponse();
        }

        redisCache.set("exeStoreSnapPinkIng"+storePinkConfig.getId(), "exeIng", 300);

        long time1=System.currentTimeMillis();
        // 查询所有拼团人数
        int allCount = storeSnapPinkDao.getAllPinkCount(storePinkConfig.getId());
        long time2=System.currentTimeMillis();


        //4,中奖标记
        //计算1~4单应该拼中人数 =总人数*中奖概率
        int hasNum =  ((BigDecimal.valueOf(allCount).multiply(storePinkConfig.getZjRate())).divide(new BigDecimal(100))).intValue();
        if(hasNum<0){
            hasNum = 0;
        }
        List<StoreSnapPink> wnningList = storeSnapPinkDao.findAllPinkWnning(storePinkConfig.getId(),hasNum);
        long time5=System.currentTimeMillis();

        //循环修改标记
        List<Long> fiveIds = new ArrayList<>();

        //中奖用户
        for(StoreSnapPink one:wnningList){
            fiveIds.add(one.getId());
        }
        if(fiveIds.size()>0){
            storeSnapPinkDao.updatePinkFives(fiveIds);
        }
        long time6=System.currentTimeMillis();

        //未中奖用户修改状态为未中奖
        int notPzNum = storeSnapPinkDao.updateNotPinkStatus(storePinkConfig.getId());
        long time7=System.currentTimeMillis();


        //  未中奖 返回订单金额 并标记订单未中奖已处理
        int notZjUserNum = userDao.updateNotSnapPz(storePinkConfig.getId(),storePinkConfig.getPrice());

        //未中奖增加订单金额退回记录
        int canclSnapPinkNum = userbillDao.addNotPzUserBill(storePinkConfig.getId());

        //修改未中奖次数
        int notZjPinkInfoNum = userSnapPinkInfoDao.updateNotPzUserPinkInfo(storePinkConfig.getId());


        //未中奖订单标记处理
        int notPzUpdateNum = storeSnapPinkDao.updateNotPzSnapPink(storePinkConfig.getId());
        long time14=System.currentTimeMillis();


        //已中奖 第五单  随机返回佣金
        for(StoreSnapPink one:wnningList){
            if(one.getStorePinkNum() == 5){//第五单

                //随机生成佣金红包
                int red_package = RandomUtil.randomNumberRangeIn(storePinkConfig.getMinRetPrice().intValue(),storePinkConfig.getMaxRetPrice().intValue());

                //增加红包记录
                snapRedPinkDao.addAutoPinkByZj(storePinkConfig.getId(),one.getUid(),one.getOrderNo(),BigDecimal.valueOf(red_package));

                //第五单赠送佣金
                userDao.addBrokerage(one.getUid(),BigDecimal.valueOf(red_package));

                //增加佣金记录
                User user  = userDao.findSingle(one.getUid());
                userPinkBillService.addUserPinkBill(one.getUid(),one.getId(), storePinkConfig.getId(),user.getBrokerage(),BigDecimal.valueOf(red_package),user.getBrokerage().add(BigDecimal.valueOf(red_package)),BillTableNameEnum.SNAP_PINK_SUCCESS.getKey(),IncomeTypeEnum.INCOME.getKey(),"抢购拼团第五单拼中获得佣金"+red_package+"元");
            }
        }
        //已中奖  标记中奖

        //已中奖 修改总中奖次数和拼团轮数
        int zjPinkInfoNum = userSnapPinkInfoDao.updatePzUserPinkInfo(storePinkConfig.getId());
        long time12=System.currentTimeMillis();

        //中奖修改 订单状态信息
        int pzSuccessNum = storeSnapPinkDao.updatePinkSuccessAddPinkNum(storePinkConfig.getId());
        long time13=System.currentTimeMillis();


        int zj_num = storeSnapPinkConfigDao.AddPinkNum(storePinkConfig.getId());

        //删除redis 执行状态标记
        redisCache.del("exeStoreSnapPinkIng"+storePinkConfig.getId());

        log.info("配置加载时间:"+(time1-time)+"ms"+ JSON.toJSONString(storePinkConfig));
        log.info("拼团总耗时:"+(time13-time));

        return new BaseResponse();
    }

}
